<?php

class Third_Grid {

    protected $_columns = array();
    protected $_options = array();
	protected $gridId;
	protected $pagerId;
	protected $filterId;

	public $caption= '';
	public $cellEdit= '';
	public $datatype= 'json';
	public $editurl= '';
	public $forcefit= true;
	public $height= '';
	public $hiddengrid= '';
	public $hidegrid= '';
	public $imgpath= '';
	public $loaderror= '';
	public $loadonce = '';
	public $mtype= '';
	public $multikey= '';
	public $multiselect= '';
	public $navGrid= '';
	public $ondblClickRow= '';
	public $onSelectRow= '';
	public $onSortCol= '';
	public $rowList= '';
	public $rowNum= 10;
	public $sortname= '';
	public $sortorder= 'ASC';
	public $subGrid= '';
	public $subGridUrl= '';
	public $url= '';
	public $viewrecords = true;
	public $width= '100%';
	public $jsonReader = ''; //'root: "rows", page: "page", total: "total", records: "records", repeatitems: false, cell: "cell"';
	public $shrinkToFit= true;
	public $gridComplete = NULL;
	
	public $isJs = false;
	public $jsFile = "/layout/third/js/jqgrid.js";
	public $jsLangFile = "/layout/third/js/jqgrid/i18n/grid.locale-en.js";
	protected $_view;
	protected $extraOptionsColumn = "gridEditOptions";

	
    /*
     * Set the Default propertys
     */
    public function __construct( $gridOptions = array() )
    {
		$this->setOptions( $gridOptions );
		
		//LOAD VIEW
		$this->_view = Zend_Registry::get('view');
		
		//JS FILES
		if( $this->isJs )
			$this->setJsFile( $this->jsFile );
    }
	/**
	 * @return the $shrinkToFit
	 */
	public function getShrinkToFit() {
		return $this->shrinkToFit;
	}

    
    /**
     * Add JS File of JqGrid
     */
    public function setJsFile( $file ){
    	$this->_view
    			->jQuery()
    			->addJavascriptFile( $this->jsLangFile )
    			->addJavascriptFile( $file )
    	;
    }

	/*
	* Set general options
	*/
	function setOptions( $options ){
		if( is_array( $options ) ){
			foreach( $options as $key=>$opt){
				switch( $key ){
					case 'caption':
						$this->setCaption( $opt );
					break;
					case 'cellEdit':
						$this->setCelledit( $opt );
					break;
					case 'datatype':
						$this->setDatatype( $opt );
					break;
					case 'editurl':
						$this->setEditurl( $opt );
					break;
					case 'forcefit':
						$this->setForcefit( $opt );
					break;
					case 'height':
						$this->setHeight( $opt );
					break;
					case 'hiddengrid':
						$this->setHiddengrid( $opt );
					break;
					case 'hidegrid':
						$this->setHidegrid( $opt );
					break;
					case 'imgpath':
						$this->setImgpath( $opt );
					break;
					case 'loaderror':
						$this->setLoaderror( $opt );
					break;
					case 'loadonce':
						$this->setLoadonce( $opt );
					break;
					case 'mtype':
						$this->setMtype( $opt );
					break;
					case 'multikey':
						$this->setMultikey( $opt );
					break;
					case 'multiselect':
						$this->setMultiselect( $opt );
					break;
					case 'navGrid':
						$this->setNavgrid( $opt );
					break;
					case 'ondblClickRow':
						$this->setOndblclickrow( $opt );
					break;
					case 'onSelectRow':
						$this->setOnselectrow( $opt );
					break;
					case 'onSortCol':
						$this->setOnsortcol( $opt );
					break;
					case 'rowList':
						$this->setRowlist( $opt );
					break;
					case 'rowNum':
						$this->setRownum( $opt );
					break;
					case 'sortname':
						$this->setSortname( $opt );
					break;
					case 'sortorder':
						$this->setSortorder( $opt );
					break;
					case 'subGrid':
						$this->setSubgrid( $opt );
					break;
					case 'subGridUrl':
						$this->setSubgridurl( $opt );
					break;
					case 'url':
						$this->setUrl( $opt );
					break;
					case 'viewrecords':
						$this->setViewrecords( $opt );
					break;
					case 'width':
						$this->setWidth( $opt );
					break;
					case 'jsonReader':
						$this->setJsonReader( $opt );
					break;
					case 'shrinkToFit':
						$this->setShrinkToFit( $opt );
					break;
					case 'gridComplete':
						$this->setGridComplete( $opt );
					break;
				}
			}
		}
	}

	/*
	* Get general options
	*/
	function getOptions( ){

		$options = array(
			'caption'=>$this->getCaption(),
			'cellEdit'=>$this->getCelledit(),
			'datatype'=>$this->getDatatype(),
			'editurl'=>$this->getEditurl(),
			'forcefit'=>$this->getForcefit(),
			'height'=>$this->getHeight(),
			'hiddengrid'=>$this->getHiddengrid(),
			'hidegrid'=>$this->getHidegrid(),
			'imgpath'=>$this->getImgpath(),
			'loaderror'=>$this->getLoaderror(),
			'loadonce'=>$this->getLoadonce(),
			'mtype'=>$this->getMtype(),
			'multikey'=>$this->getMultikey(),
			'multiselect'=>$this->getMultiselect(),
			'navGrid'=>$this->getNavgrid(),
			'ondblClickRow'=>$this->getOndblclickrow(),
			'onSelectRow'=>$this->getOnselectrow(),
			'onSortCol'=>$this->getOnsortcol(),
			'rowList'=>$this->getRowlist(),
			'rowNum'=>$this->getRownum(),
			'sortname'=>$this->getSortname(),
			'sortorder'=>$this->getSortorder(),
			'subGrid'=>$this->getSubgrid(),
			'subGridUrl'=>$this->getSubgridurl(),
			'url'=>$this->getUrl(),
			'viewrecords'=>$this->getViewrecords(),
			'width'=>$this->getWidth(),
			'jsonReader'=>$this->getJsonReader( ),
			'shrinkToFit'=>$this->getShrinkToFit(),
			//, 'gridComplete'=>$this->getGridComplete()
		);
		
		return $options;
	}
	/**
	 * @param $extraOptionsColumn the $extraOptionsColumn to set
	 */
	public function setExtraOptionsColumn($extraOptionsColumn) {
		$this->extraOptionsColumn = $extraOptionsColumn;
	}

	/**
	 * @return the $extraOptionsColumn
	 */
	public function getExtraOptionsColumn() {
		return $this->extraOptionsColumn;
	}

	/**
	 * @param $filterId the $filterId to set
	 */
	public function setFilterId($filterId) {
		$this->filterId = $filterId;
	}

	/**
	 * @param $pagerId the $pagerId to set
	 */
	public function setPagerId($pagerId) {
		$this->pagerId = $pagerId;
	}

	/**
	 * @param $gridId the $gridId to set
	 */
	public function setGridId($gridId) {
		$this->gridId = $gridId;
	}

	/**
	 * @return the $filterId
	 */
	public function getFilterId() {
		return $this->filterId;
	}

	/**
	 * @return the $pagerId
	 */
	public function getPagerId() {
		return $this->pagerId;
	}

	/**
	 * @return the $gridId
	 */
	public function getGridId() {
		return $this->gridId;
	}

	
	/**
	 * return $getGridComplete function
	 */
	public function getGridComplete(){
		return $this->gridComplete;
	}
	
	/**
	 * @param $shrinkToFit the $shrinkToFit to set
	 */
	public function setShrinkToFit($shrinkToFit) {
		$this->shrinkToFit = $shrinkToFit;
	}

	/**
	 * @param $jsonReader the $jsonReader to set
	 */
	public function setJsonReader($jsonReader) {
		$this->jsonReader = $jsonReader;
	}

	/**
	 * @return the $jsonReader
	 */
	public function getJsonReader() {
		return $this->jsonReader;
	}


	/**
	 * @param $width the $width to set
	 */
	public function setWidth($width) {
		$this->width = $width;
	}

	/**
	 * @param $viewrecords the $viewrecords to set
	 */
	public function setViewrecords($viewrecords) {
		$this->viewrecords = $viewrecords;
	}

	/**
	 * @param $url the $url to set
	 */
	public function setUrl($url) {
		$this->url = $url;
	}

	/**
	 * @param $subGridUrl the $subGridUrl to set
	 */
	public function setSubGridUrl($subGridUrl) {
		$this->subGridUrl = $subGridUrl;
	}

	/**
	 * @param $subGrid the $subGrid to set
	 */
	public function setSubGrid($subGrid) {
		$this->subGrid = $subGrid;
	}

	/**
	 * @param $sortorder the $sortorder to set
	 */
	public function setSortorder($sortorder) {
		$this->sortorder = $sortorder;
	}

	/**
	 * @param $sortname the $sortname to set
	 */
	public function setSortname($sortname) {
		$this->sortname = $sortname;
	}

	/**
	 * @param $rowNum the $rowNum to set
	 */
	public function setRowNum($rowNum) {
		$this->rowNum = $rowNum;
	}

	/**
	 * @param $rowList the $rowList to set
	 */
	public function setRowList($rowList) {
		$this->rowList = $rowList;
	}

	/**
	 * @param $onSortCol the $onSortCol to set
	 */
	public function setOnSortCol($onSortCol) {
		$this->onSortCol = $onSortCol;
	}

	/**
	 * @param $onSelectRow the $onSelectRow to set
	 */
	public function setOnSelectRow($onSelectRow) {
		$this->onSelectRow = $onSelectRow;
	}

	/**
	 * @param $ondblClickRow the $ondblClickRow to set
	 */
	public function setOndblClickRow($ondblClickRow) {
		$this->ondblClickRow = $ondblClickRow;
	}

	/**
	 * @param $navGrid the $navGrid to set
	 */
	public function setNavGrid($navGrid) {
		$this->navGrid = $navGrid;
	}

	/**
	 * @param $multiselect the $multiselect to set
	 */
	public function setMultiselect($multiselect) {
		$this->multiselect = $multiselect;
	}

	/**
	 * @param $multikey the $multikey to set
	 */
	public function setMultikey($multikey) {
		$this->multikey = $multikey;
	}

	/**
	 * @param $mtype the $mtype to set
	 */
	public function setMtype($mtype) {
		$this->mtype = $mtype;
	}

	/**
	 * @param $loadonce the $loadonce to set
	 */
	public function setLoadonce($loadonce) {
		$this->loadonce = $loadonce;
	}

	/**
	 * @param $loaderror the $loaderror to set
	 */
	public function setLoaderror($loaderror) {
		$this->loaderror = $loaderror;
	}

	/**
	 * @param $imgpath the $imgpath to set
	 */
	public function setImgpath($imgpath) {
		$this->imgpath = $imgpath;
	}

	/**
	 * @param $hidegrid the $hidegrid to set
	 */
	public function setHidegrid($hidegrid) {
		$this->hidegrid = $hidegrid;
	}

	/**
	 * @param $hiddengrid the $hiddengrid to set
	 */
	public function setHiddengrid($hiddengrid) {
		$this->hiddengrid = $hiddengrid;
	}

	/**
	 * @param $height the $height to set
	 */
	public function setHeight($height) {
		$this->height = $height;
	}

	/**
	 * @param $forcefit the $forcefit to set
	 */
	public function setForcefit($forcefit) {
		$this->forcefit = $forcefit;
	}

	/**
	 * @param $editurl the $editurl to set
	 */
	public function setEditurl($editurl) {
		$this->editurl = $editurl;
	}

	/**
	 * @param $datatype the $datatype to set
	 */
	public function setDatatype($datatype) {
		$this->datatype = $datatype;
	}

	/**
	 * @param $cellEdit the $cellEdit to set
	 */
	public function setCellEdit($cellEdit) {
		$this->cellEdit = $cellEdit;
	}

	/**
	 * @param $caption the $caption to set
	 */
	public function setCaption($caption) {
		$this->caption = $caption;
	}

	/**
	 * @return the $width
	 */
	public function getWidth() {
		return $this->width;
	}

	/**
	 * @return the $viewrecords
	 */
	public function getViewrecords() {
		return $this->viewrecords;
	}

	/**
	 * @return the $url
	 */
	public function getUrl() {
		return $this->url;
	}

	/**
	 * @return the $subGridUrl
	 */
	public function getSubGridUrl() {
		return $this->subGridUrl;
	}

	/**
	 * @return the $subGrid
	 */
	public function getSubGrid() {
		return $this->subGrid;
	}

	/**
	 * @return the $sortorder
	 */
	public function getSortorder() {
		return $this->sortorder;
	}

	/**
	 * @return the $sortname
	 */
	public function getSortname() {
		return $this->sortname;
	}

	/**
	 * @return the $rowNum
	 */
	public function getRowNum() {
		return $this->rowNum;
	}

	/**
	 * @return the $rowList
	 */
	public function getRowList() {
		return $this->rowList;
	}

	/**
	 * @return the $onSortCol
	 */
	public function getOnSortCol() {
		return $this->onSortCol;
	}

	/**
	 * @return the $onSelectRow
	 */
	public function getOnSelectRow() {
		return $this->onSelectRow;
	}

	/**
	 * @return the $ondblClickRow
	 */
	public function getOndblClickRow() {
		return $this->ondblClickRow;
	}

	/**
	 * @return the $navGrid
	 */
	public function getNavGrid() {
		return $this->navGrid;
	}

	/**
	 * @return the $multiselect
	 */
	public function getMultiselect() {
		return $this->multiselect;
	}

	/**
	 * @return the $multikey
	 */
	public function getMultikey() {
		return $this->multikey;
	}

	/**
	 * @return the $mtype
	 */
	public function getMtype() {
		return $this->mtype;
	}

	/**
	 * @return the $loadonce
	 */
	public function getLoadonce() {
		return $this->loadonce;
	}

	/**
	 * @return the $loaderror
	 */
	public function getLoaderror() {
		return $this->loaderror;
	}

	/**
	 * @return the $imgpath
	 */
	public function getImgpath() {
		return $this->imgpath;
	}

	/**
	 * @return the $hidegrid
	 */
	public function getHidegrid() {
		return $this->hidegrid;
	}

	/**
	 * @return the $hiddengrid
	 */
	public function getHiddengrid() {
		return $this->hiddengrid;
	}

	/**
	 * @return the $height
	 */
	public function getHeight() {
		return $this->height;
	}

	/**
	 * @return the $forcefit
	 */
	public function getForcefit() {
		return $this->forcefit;
	}

	/**
	 * @return the $editurl
	 */
	public function getEditurl() {
		return $this->editurl;
	}

	/**
	 * @return the $datatype
	 */
	public function getDatatype() {
		return $this->datatype;
	}

	/**
	 * @return the $cellEdit
	 */
	public function getCellEdit() {
		return $this->cellEdit;
	}

	/**
	 * @return the $caption
	 */
	public function getCaption() {
		return $this->caption;
	}


    /*
     * Add the Column values
     * param Array[]
     */
    public function addColumn( $data )
    {
        $this->_columns[] = $data;
    }

    /*
     * Return the columns values
     * param Array[]
     */
    public function getColumns( ){
    	return $this->_columns;
    }

    /*
     *  Generate Javascript for Grid
     */
    public function get( $gridId, $pagerId = "", $filterId="" )
    {
    	$this->setGridId( $gridId );
    	$this->setPagerId( $pagerId );
    	$this->setFilterId( $filterId );
    	
    	//GET CODE
          $js  = $this->getGridJS( $gridId );
          $js .= "".$this->getColumnsJS();
          $js .= "".$this->getParamsJS();
          $js .= "".$this->getSubGridRowExpandedJS();
          $js .= "".$this->getPagerJS( $pagerId );
          $js .= "".$this->getFilterJS( $filterId, $gridId);
        return $js;
    }
    
    public function show( $gridId, $pagerId = "", $filterId="" ){
    	$this->_view->jQuery()->onLoadCaptureStart();
    		echo $this->get( $gridId, $pagerId, $filterId );
    	$this->_view->jQuery()->onLoadCaptureEnd();
    }

    /*
     * Initial function for jqGrid
     */
    protected function getGridJS( $gridId )
    {
        return "$('" . $gridId . "').jqGrid({";
    }

	/*
	* Return columns as array
	*/
	public function getColumnsArray(){
		$columns = array();

		foreach( $this->getColumns() as $column ){
			if( is_array( $column ) ){
				$columns[ $column['name'] ] = $column;
			} elseif( get_class($column) == 'Third_Grid_Column' ){
				$columns[ $column->getName() ] = $column->get();
			}
		}

		return $columns;
	}

    /*
     * Generate the javascript for column setup part
     */
    public function getColumnsJS()
    {
    	$columns = $this->getColumnsArray();

        $js = "colNames:[";
        $cnt = count( $columns );

        foreach( $columns as $col ){
            $js = $js . "'" . $col['name'] . "',";
        }
        if ($cnt>0) {
            $js = substr($js, 0, -1);
        }
        $js = $js . "], colModel:[";


        foreach( $columns as $col ) {
            $js = $js . "\t{";
            foreach ( $col as $property => $value ) {
                if ( $property != 'name' ) {
                    if ( is_numeric($value) ) {
                        $js = $js . $property .":" . $value . ",";
                    }elseif ( is_string($value) ) {
                        $js = $js . $property .":'" . $value . "',";
                    }
                }
            }
            $js = substr($js, 0, -1) . "},";
        }
        if ($cnt>0) {
            $js = substr($js, 0, -1);
        }
        $js = $js . "],";

        return $js;
    }

    /*
     *   Generate js for Others Properties
     */
    protected function getParamsJS()
    {
    	$js = "";
    	$options = $this->getOptions();
    	
        foreach ( $options as $property => $value ){
            if ( $property != 'navGrid' && $property !='gridComplete') {
                if ( $value != '' && is_string($value) && substr($value,0,1) != "'" )  {
                    $js = $js . $property . ":'" . $value . "',";
                }elseif( is_array($value) )  {
                    $js = $js . $property . ":[";
                        foreach($value as $val) {
                            $js = $js . $val . ",";
                        }
                        $js = substr($js, 0, -1) . "],";
                }elseif( is_bool($value)) {
                    $js = $js . $property . ":" . ($value ?  "true," : "false,");
                }elseif( $value != '' ) {
                    $js = $js . $property . ":" . $value . ",";
                }
            } elseif($property == 'gridComplete' ){
            	 $js = $js .$property . ":" . $value . ",";
            }
        }
        return substr($js, 0, -1);
    }

    protected function getSubGridRowExpandedJS(){

    }

    /*
     *   Generate Javascript for Pager part.
     */
    protected function getPagerJS( $pagerId )
    {
    	$options = $this->getOptions();
    	
        if ( $pagerId == '' ) {
            return '});';
        }else{
            $js = ",pager:$('" . $pagerId . "')";
            if ( is_array( $options['navGrid']) ) {
                  $js = $js . "}).navGrid('" .  $pagerId .
                                        "',{edit:" . ($options['navGrid']['edit'] ? "true" : "false") .
                            ",add:" . ($options['navGrid']['add'] ? "true" : "false") .
                            ",del:" . ($options['navGrid']['del'] ? "true" : "false");
                  if ( isset($options['navGrid']['position']) ) {
                      $js = $js . ",position:" . $options['navGrid']['position'];
                  }
            }
            return $js . "});";
        }
    }

    /*
     *  Generate javascript for filterGrid
     */
    protected function getFilterJS( $filterId, $gridId )
    {
        if ( $filterId == '' ) {
           // return '});';
        }else{
            $id = substr($gridId, 1);
            $js = "$('" . $filterId . "').filterGrid('" . $id . "',{";
            $js .= "gridModel:true, gridNames: true, formtype: 'vertical', enableSearch: true, enableClear:true, autosearch: false";
            $js .= "});";
            return $js;
        }
    }
}

?>